package GUI;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.sf.feeling.swt.win32.extension.Win32;
import org.sf.feeling.swt.win32.extension.hook.Hook;
import org.sf.feeling.swt.win32.extension.hook.data.HookData;
import org.sf.feeling.swt.win32.extension.hook.data.KeyboardHookData;
import org.sf.feeling.swt.win32.extension.hook.listener.HookEventListener;
import org.sf.feeling.swt.win32.extension.shell.Windows;

/**This class allows program to receive global hotkey in the form
 * button A + button B.
 * @author Defeng
 *
 */
public class win32KeyHook {
	
//only need to change this 2 variable to change global hotkey
public long KEY01 = 18;  //a ALT button  
public long KEY02 = 192; //a ~ button

private long curKey=0;
private long key01=KEY01;
private long key02=0;

private boolean key01pressed = false;
private Composite shell;

//constructor + initialize hook
/**Constructor for the class.
 * Install the hook into windows and sets up code to detect 2 specified button pressed.
 * User has to manually un-install the hook when the programs closes.
 * @param object
 * @param Display
 */
public win32KeyHook(final Composite object, final Display Display){
	shell = object;	
	Hook.KEYBOARD.install(object);
	Hook.KEYBOARD.addListener( object, new HookEventListener( ) {

	public void acceptHookData( final HookData hookData )
	{
		if ( hookData != null )
		{
			Display.asyncExec( new Runnable( ) {

				public void run( ) {
					if ( Hook.KEYBOARD.isInstalled( object )  
						&& ( (KeyboardHookData) hookData ).getTransitionState()) {
					/*
						System.out.println( "Virtual Key Code = "
								+ ( (KeyboardHookData) hookData ).getVirtualKeyCode( )
								+ ", Scan Code = "
								+ ( (KeyboardHookData) hookData ).getScanCode( )
								+ ", Extended Key = "
								+ ( (KeyboardHookData) hookData ).isExtendedKey( ) );
					*/
					curKey = ( (KeyboardHookData) hookData ).getVirtualKeyCode( );
					
							if(curKey == KEY01)	key01pressed = true; 
							if(key01pressed && curKey == KEY02)	{key02 = curKey; toggleKeyState();}
					}
					
				};
			} );
		}
	}
} );

}
	
	private void toggleKeyState(){	
		Windows.setWindowAlwaysOnTop(shell.handle, true);
		Windows.setWindowAlwaysOnTop(shell.handle, false);
		//Windows.setWindowMinimized(shell.handle);
		Windows.setWindowRestored(shell.handle);
		System.out.println(">"+key01+"<,>"+key02+"<"+"\n-----@ ");
		
		//reset booleans
		key01pressed = false;
	}

	/**Uninstall the hook
	 * @param object
	 */
	public void removeHook(final Composite object){
		Hook.KEYBOARD.uninstall( object);
	}
	
	
	
}
